"use client"
import ErrorMessage from "@/app/components/ErrorMessage";
import Spinner from "@/app/components/spinner";
import {createIssueSchema} from "@/app/validationSchemas";
import {Button, Callout, TextField} from "@radix-ui/themes";
import React, {useState} from "react";
import "easymde/dist/easymde.min.css";

import {useForm,Controller} from "react-hook-form";
import axios from "axios";
import {useRouter} from "next/navigation";
import {zodResolver} from "@hookform/resolvers/zod";
import z from "zod";
import dynamic from "next/dynamic";
import {Issue} from ".prisma/client";
import SimpleMDE from 'react-simplemde-editor';

type IssueForm= z.infer<typeof createIssueSchema>

interface Props{
    issue?:Issue
}

const IssueForm = ({issue}:Props)=>{
    const {register,control,handleSubmit,formState:{errors}} = useForm<IssueForm>({
        resolver:zodResolver(createIssueSchema)
    });
    const router = useRouter();
    const [error,setError] = useState("");
    const [isSubmitting,setSubmitting] = useState(false);
    const onSubmit = handleSubmit(async (data)=>{
        try{
            setSubmitting(true);
            if(issue) await axios.patch("/api/issues/"+issue.id,data);
            else await axios.post("/api/issues/",data);
            router.push("/issues")
            router.refresh();
        }catch (e){
            setSubmitting(false);
            setError("An unexpected error occurred.");
        }
    })
    return(
        <div className={"max-w-xl"}>
            {error&&(<Callout.Root color={"red"} className={"mb-5"}>
                <Callout.Text>{error}</Callout.Text>
            </Callout.Root>)}
            <form className={"space-y-3"}
                  onSubmit={onSubmit}
            >
                <TextField.Root>
                    <TextField.Input
                        placeholder={"title"}
                        defaultValue={issue?.title}
                        {...register("title")}/>
                </TextField.Root>
                <ErrorMessage>{errors.title?.message}</ErrorMessage>
                <Controller
                    name={"description"}
                    render={
                        ({field})=>(
                            <SimpleMDE placeholder={"Description"} {...field}/>
                        )
                    }
                    control={control}
                    defaultValue={issue?.description}
                />
                <ErrorMessage>{errors.description?.message}</ErrorMessage>
                <Button disabled={isSubmitting}>
                    {issue?"Update Issue":"Submit New Issue"}
                    {isSubmitting&&<Spinner/>}
                </Button>
            </form>
        </div>

    )
}

export default IssueForm;